const sha256 = require('./sha256.js')
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}


const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}
// 倒计时
function countDown(that) { //倒计时函数
  let newTime = new Date().getTime();
  let endTime = that.data.endTime;
  let remainTime = endTime - newTime;
  let obj = null;
  let t = '';
  // 如果活动未结束，对时间进行处理
  if (remainTime > 0) {
    let time = remainTime / 1000;
    // 获取天、时、分、秒
    let day = parseInt(time / (60 * 60 * 24));
    let hou = parseInt(time % (60 * 60 * 24) / 3600);
    let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
    let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
    obj = {
      day: formatNumber(day),
      hou: formatNumber(hou),
      min: formatNumber(min),
      sec: formatNumber(sec)
    }
  }
  t = setTimeout(function () {
    that.setData({
      countDownTxt: obj
    });
    countDown(that)
  }, 1000)
  if (remainTime <= 0) {
    clearTimeout(t);
  }
}
function xAjax(url, data, success, error) {
  var timestamp = parseInt(new Date().getTime() / 1000);
  var appSecret = "f995e2f587739f159af18d0e5dc921b0";
  var appId = "70782ba1d6626f2cb3cfed5cfcf3ed31";
  var sign = sha256.sha256_digest(appSecret+"&"+timestamp+"&"+JSON.stringify(data));
  wx.request({
    url: "http://luhu-test3.crm.luxelakes.com/api/"+url,
    method: 'POST',
    header: {
      'content-type': 'application/json',
      'X-AppId': appId,
      'X-Sign': sign,
      'X-Timestamp': timestamp
    },
    data: data,
    success: function (res) {
      typeof success == "function" && success(res.data)
    },
    fail: function () {
      typeof error == "function" && error()
    }
  });

}
module.exports = {
  formatTime,
  xAjax: xAjax,
  countDown: countDown
}
